const dbQuery = require('../model/db');
const bcryptjs = require('bcryptjs');
const jwtoken = require('jsonwebtoken');
const joi = require('joi');
const {
	sendError,
	sendSuccess
} = require('../utils/sendFunction');

// 生成token所用的字符串
const str = 'secret';

// 验证规则
// 用户名和密码 4-12位
const schemaLogin = joi.object({
	username: joi.string().min(4).max(12).alphanum().required().error(new Error('username不符合验证规则')),
	password: joi.string().min(4).max(12).required().error(new Error('password不符合验证规则'))
})

// 管理员
// username password
const admin = async function (req, res, next) {
	let {
		username,
		password
	} = req.body;

	if (!username || !password) {
		sendError(res, 200, '用户名或密码不能为空!');
		return;
	}

	try {
		await schemaLogin.validateAsync({
			username,
			password
		})
	} catch (error) {
		next(error);
		return;
	}

	let sqlStr = 'select * from admin where username=?';
	let result = await dbQuery(sqlStr, [username]);
	if (result.length == 0) {
		sendError(res, 200, '登录失败,请注册后重新登录!');
		return;
	}

	let isVal = await bcryptjs.compare(password, result[0].password);
	if (isVal) {
		// 生成token
		sendSuccess(res, '登录成功!', {
			token: 'Bearer ' + jwtoken.sign({
				username: result[0].username,
				id: result[0].adminid
			}, str, {
				expiresIn: '48h'
			})
		})
	} else {
		sendError(res, 200, '用户名或密码错误!');
	}
}

// 用户
// username password
const user = async function (req, res, next) {
	let {
		username,
		password
	} = req.body;

	if (!username || !password) {
		sendError(res, 200, '用户名或密码不能为空!');
		return;
	}

	try {
		await schemaLogin.validateAsync({
			username,
			password
		})
	} catch (error) {
		next(error);
		return;
	}

	let sqlStr = 'select * from user where username=?';
	let result = await dbQuery(sqlStr, username);
	if (result.length == 0) {
		sendError(res, 200, '登录失败,请注册后重新登录!');
		return;
	}

	let isVal = await bcryptjs.compare(password, result[0].password);
	if (isVal) {
		// 生成token
		sendSuccess(res, '登陆成功!', {
			token: 'Bearer ' + jwtoken.sign({
				username: result[0].username,
				id: result[0].userid
			}, str, {
				expiresIn: '48h'
			}),
			data: {
				userid: result[0].userid
			}
		})
	} else {
		sendError(res, 200, '用户名或密码错误!');
	}
}


module.exports = {
	admin,
	user
}